// pages/Home/TravelDetail/TravelDetail.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryTravelItemPlan , queryTravelItemPlanDate , updateTravelItemCollect , queryTravelItemInfo } from '../../../api/travel';
import { addZero } from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    travel: {},
    itemPlanList: [], // 套餐列表
    planId: '', // 选择的套餐ID
    planPage: 0,
    isPlanReachBottom: true,
    itemPlanDateList: [], // 套餐日期列表
    planDateId: '', // 选择的套餐日期ID
    planDatePage: 0,
    isPlanDateReachBottom: true,
    showPlanDateVisible: false,
    minDate: new Date().getTime(),
    formatter: function(day){
      return day;
    },
    travelInfo: [], // 旅游详细信息
    active: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.item){
      var item = JSON.parse(options.item);
      console.log(item,'item')
      this.setData({
        travel: item,
        // travelInfo: item.itemInfo,
        // travelInfoImgList: item.itemInfo.length > 0 ? item.itemInfo[0].imgUrlList : [],
      })
      wx.setNavigationBarTitle({
        title: item.title.title,
      })
      this._queryTravelItemPlan();
      this._queryTravelItemInfo();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 查询套餐详情
  _queryTravelItemPlan(){
    let _this = this;
    queryTravelItemPlan({itemId: _this.data.travel.id,page: _this.data.planPage})
    .then(res => {
      if(res.success){
        var list = _this.data.itemPlanList;
        if(_this.data.planPage == 0){
          list = res.data.content;
          _this.setData({
            planId: list.length > 0 ? list[0]['id'] : '',
          })
          if(list.length > 0){
            _this._queryTravelItemPlanDate();
          }
        }else{
          list = list.concat(res.data.content);
        }
        _this.setData({
          itemPlanList: list,
          total: res.data.totalElements,
          planPage: _this.data.planPage+1,
        })
        if(_this.data.planPage * 10 >= res.data.totalElements){
          _this.setData({
            isPlanReachBottom: false,
            noMore: true,
          })
        }else{
          _this.setData({
            isPlanReachBottom: true,
            noMore: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 切换套餐
  selPlan(e){
    console.log(e,'切换套餐事件');
    this.setData({
      planId: e.detail.id,
    })
    this._queryTravelItemPlanDate();
  },
  // 套餐列表触底事件
  onPlanReachBottom(){
    console.log('套餐加载更多')
    if(this.data.isPlanReachBottom){
      this._queryTravelItemPlan()
    }
  },
  // 查询套餐日期数据
  _queryTravelItemPlanDate(){
    let _this = this;
    queryTravelItemPlanDate({itemId: _this.data.travel.id,planId: _this.data.planId,page: _this.data.planDatePage})
    .then(res => {
      if(res.success){
        let list = res.data;
        list = list.sort((a,b)=> new Date(a.travelDate).getTime() - new Date(b.travelDate).getTime());
        let arr = [];
        for (let index = 0; index < list.length; index++) {
          const element = list[index];
          let date = new Date(element.travelDate);
          let nowDate = new Date();
          if(nowDate.getTime() < date.getTime() || (nowDate.getTime() > date.getTime() && nowDate.getDate() == date.getDate())){
            arr.push(element);
          }
        }
        _this.setData({
          planDateId: arr.length > 0 ? arr[0]['id'] : '',
        })
        _this.setData({
          itemPlanDateList: arr,
          planDatePage: _this.data.planDatePage+1,
        })
        if(_this.data.planDatePage * 10 >= res.data.totalElements){
          _this.setData({
            isPlanDateReachBottom: false,
          })
        }else{
          _this.setData({
            isPlanDateReachBottom: true,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 切换套餐日期
  selPlanDate(e){
    console.log(e,'切换套餐日期事件');
    this.setData({
      planDateId: e.detail.id,
    })
  },
  // 更多套餐日期
  morePlanDate(){
    let _this = this;
    _this.setData({
      showPlanDateVisible: true,
      formatter: function(day){
        const year = day.date.getFullYear();
        const month = day.date.getMonth() + 1;
        const date = day.date.getDate();
        var dates = `${year}-${addZero(month)}-${addZero(date)}`;
        for (let index = 0; index < _this.data.itemPlanDateList.length; index++) {
          const itm = _this.data.itemPlanDateList[index];
          if(itm.travelDate == dates){
            day.bottomInfo = `￥${itm.amount}`;
          }
        }
        return day;
      }
    })
  },
  // 确认选择套餐日期
  onPlanDateConfirm(event){
    let _this = this;
    console.log(event,'event')
    var selDate = new Date(event.detail);
    var year = selDate.getFullYear();
    var month = selDate.getMonth() + 1;
    var date = selDate.getDate();
    var dates = `${year}-${addZero(month)}-${addZero(date)}`;
    var planDateId = '';
    for (let index = 0; index < _this.data.itemPlanDateList.length; index++) {
      const itm = _this.data.itemPlanDateList[index];
      if(itm.travelDate == dates){
        planDateId = itm.id;
      }
    }
    if(planDateId == ''){
      wx.showToast({
        title: '当前日期暂无价格信息，请更换其他日期',
        icon: 'none',
      });
      return;
    }else{
      _this.setData({
        showPlanDateVisible: false,
        planDateId: planDateId,
      })
    }
  },
  planDateClose(){
    this.setData({showPlanDateVisible: false})
  },
  // 旅游详情切换
  onTravelInfoChange(e){
    console.log(e.detail)
    let _this = this;
    this.setData({
      active: e.detail.index,
      travelInfoImgList: _this.data.travelInfo[e.detail.index].imgUrlList,
    })
  },
  // 订购旅游商品
  submitOrder(){
    console.log(this.data.travel,'travel')
    console.log(this.data.planId,'planId');
    const itemPlan = this.data.itemPlanList.find(itm => itm.id == this.data.planId);
    console.log(itemPlan,'itemPlan');
    console.log(this.data.itemPlanList,'itemPlanList');
    console.log(this.data.planDateId,'planDateId');
    const itemPlanDate = this.data.itemPlanDateList.find(itm => itm.id == this.data.planDateId);
    console.log(itemPlanDate,'itemPlanDate');
    console.log(this.data.itemPlanDateList,'itemPlanDateList');
    if(!itemPlan){
      wx.showToast({
        title: '暂无相关套餐信息，请更换套餐或更换其他旅游项目',
        icon: 'none'
      })
      return;
    }
    if(!itemPlanDate){
      wx.showToast({
        title: '暂无相关套餐日期价格信息，请更换套餐日期或更换其他套餐信息',
        icon: 'none'
      })
      return;
    }
    const item = {
      'travel': this.data.travel,
      'planId': this.data.planId,
      'plan': itemPlan,
      'planDateId': this.data.planDateId,
      'planDate': itemPlanDate,
    };
    wx.navigateTo({
      url: `/pages/Order/SubmitTravelOrder/SubmitTravelOrder?travelItem=${JSON.stringify(item)}`,
    })
  },
  // 收藏
  collect(){
    let _this = this;
    updateTravelItemCollect({itemId: _this.data.travel.id,itemType: _this.data.travel.itemType,isDelete: _this.data.travel.isCollect})
    .then(res => {
      if(res.success){
        const eventChannel = _this.getOpenerEventChannel();
        eventChannel.emit('updateData',);
        wx.showToast({
          title: _this.data.travel.isCollect  == '1' ? '取消收藏' : '收藏成功',
          icon: 'success',
        })
        let travel = _this.data.travel;
        travel.isCollect = travel.isCollect == '1' ? '0' : '1';
        _this.setData({
          travel: travel,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  _queryTravelItemInfo(){
    let _this = this;
    queryTravelItemInfo({itemId: _this.data.travel.id})
    .then(res => {
      if(res.success){
        let arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          element.imgUrlList = element.imgUrl.split(',');
          arr.push(element);
        }
        _this.setData({
          travelInfo: arr,
          travelInfoImgList: arr.length > 0 ? arr[0].imgUrlList : []
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})